/*
 * Copyright 2010 J Patrick Davenport
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package v4view.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

/**
 * Represents a standard table in html.
 * @author J Patrick Davenport
 *
 */
// TODO Finish this
public class Table extends TableElement {
	private static final String	CAPTION_KEY		= "caption";
	private static final String	RULES_KEY		= "rules";
	private static final String	FRAME_KEY		= "frame";
	private static final String	BORDER_KEY		= "border";
	private static final String	CELLPADDING_KEY	= "cellpadding";
	private static final String	CELLSPACING_KEY	= "cellspacing";
	private static final String	TABLE_TAG		= "table";
	private boolean				hasTBody;
	private boolean				hasTr;
	private boolean				hasTHead;

	private String				headId;
	private String				tfootId;
	private String				captionId;
	private boolean				hasTFoot;

	{
		this.setTag(TABLE_TAG);
		this.setSupportsAttributes(true);
	}

	public Integer getCellSpacing() {
		final String attributeValue = this.getAttributeValue(CELLSPACING_KEY);

		return StringUtils.isEmpty(attributeValue) ? null : Integer.valueOf(attributeValue);
	}

	public Table setCellSpacing(final int _value) {
		return (Table) this.setAttribute(CELLSPACING_KEY, String.valueOf(_value));
	}

	public Integer getCellPadding() {
		final String attributeValue = this.getAttributeValue(CELLPADDING_KEY);

		return StringUtils.isEmpty(attributeValue) ? null : Integer.valueOf(attributeValue);
	}

	public Table setFrame(final Frame _value) {
		return (Table) this.setAttribute(FRAME_KEY, _value == null ? null : _value.toString());
	}

	public Frame getFrame() {
		final String attributeValue = this.getAttributeValue(FRAME_KEY);
		if (StringUtils.isEmpty(attributeValue)) { return null; }
		return Enum.valueOf(Frame.class, attributeValue.toUpperCase());
	}

	public Table setRules(final Rules _value) {
		return (Table) this.setAttribute(RULES_KEY, _value == null ? null : _value.toString());
	}

	public Rules getRules() {
		final String attributeValue = this.getAttributeValue(RULES_KEY);
		if (StringUtils.isEmpty(attributeValue)) { return null; }
		return Enum.valueOf(Rules.class, attributeValue.toUpperCase());
	}

	public Table setCellPadding(final int _value) {
		return (Table) this.setAttribute(CELLPADDING_KEY, String.valueOf(_value));
	}

	public Integer getBorder() {
		final String attributeValue = this.getAttributeValue(BORDER_KEY);

		return StringUtils.isEmpty(attributeValue) ? null : Integer.valueOf(attributeValue);
	}

	public Table setBorder(final Integer _value) {
		return (Table) this.setAttribute(BORDER_KEY, String.valueOf(_value));
	}

	public Table setCaption(final Caption _caption) {
		if (_caption == null) { return this; }
		this.prepCaption(_caption);
		this.addPageElement(_caption);

		return this;
	}

	private void prepCaption(final Caption _caption) {
		this.removePageElement(_caption);
		_caption.setElementId(CAPTION_KEY);
	}

	public Table setCaption(final String _captionText) {
		if (StringUtils.isEmpty(_captionText)) return this;
		this.setCaption(new Caption(_captionText));
		return this;
	}

	public Caption getCaption() {
		final Caption findElement = (Caption) this.findElement(this.captionId);
		return findElement;
	}

	@Override
	public void render() throws IOException {
		if (this.hasChildren()) {
			final Caption caption = this.getCaption();
			final THead head = this.getHead();
			final List<TBody> bodies = this.getBodies();
			final TFoot foot = this.getFoot();
			final List<Tr> rows = this.getRows();

			this.removeAllChildren();
			this.hasTBody = this.hasTFoot = this.hasTHead = false;
			if (caption != null) {
				this.addPageElement(caption);
			}

			if (head != null) {
				this.addPageElement(head);
			}

			for (final TBody b : bodies) {
				this.addPageElement(b);
			}

			for (final Tr tr : rows) {
				this.addPageElement(tr);
			}

			if (foot != null) {
				this.addPageElement(foot);
			}
			super.render();
		}
	}

	/**
	 * Only accepts Tr, THead, TFoot, Caption and TBody. Any other element will be silently ignored.
	 * <p>
	 * Adding rules are as followed.
	 * 	<ul>
	 * 		<li>If a {@link Caption} is passed in, any other caption is overwritten.
	 *  	<li>If a {@link THead} is passed in and the table already has a head, the new value is ignored.</li>
	 *  	<li>If a {@link TBody} is passed in and the table already has a tr, the new value is ignored.</li>
	 * 		<li>If a {@link TBody} is passed in and the table already has a body, the new value is added after the .</li>
	 *  	<li>If a {@link Tr} is passed in and the table already has a body, the Tr is ignored.</li>
	 *  </ul>
	 * </p>	
	 * 
	 */
	@Override
	public Table addPageElement(final PageElement _element) {
		if ((_element instanceof Tr) && !this.hasTBody) {
			this.hasTr = true;
			super.addPageElement(_element);
		} else if ((_element instanceof TBody) && !this.hasTr) {
			this.hasTBody = true;
			super.addPageElement(_element);
		} else if ((_element instanceof THead) && !this.hasTHead) {
			this.hasTHead = true;
			this.headId = "head" + System.currentTimeMillis();
			_element.setElementId(this.headId);
			super.addPageElement(_element);
			this.headId = _element.getElementId();
		} else if ((_element instanceof TFoot) && !this.hasTFoot) {
			this.hasTFoot = true;
			this.tfootId = "foot" + System.currentTimeMillis();
			_element.setElementId(this.tfootId);
			super.addPageElement(_element);
			this.tfootId = _element.getElementId();
		} else if (_element instanceof Caption) {
			this.prepCaption((Caption) _element);
			super.addPageElement(_element);
			this.captionId = _element.getElementId();
		}
		return this;
	}

	public THead getHead() {
		return (THead) this.findElement(this.headId);
	}

	/**
	 * Finds all of the TBodies in the table.
	 * @return an unmodifiable list of bodies found in the table.
	 */
	public List<TBody> getBodies() {
		final ArrayList<TBody> bodies = this.findMyBodies();
		return Collections.unmodifiableList(bodies);
	}

	private ArrayList<TBody> findMyBodies() {
		final ArrayList<TBody> bodies = new ArrayList<TBody>();
		final List<PageElement> children = this.getChildren();
		for (final PageElement element : children) {
			if (element instanceof TBody) {
				bodies.add((TBody) element);
			}
		}
		return bodies;
	}

	public TFoot getFoot() {
		return (TFoot) this.findElement(this.tfootId);
	}

	public List<Tr> getRows() {
		final ArrayList<Tr> rows = new ArrayList<Tr>();
		final List<PageElement> children = this.getChildren();
		for (final PageElement element : children) {
			if (element instanceof Tr) {
				rows.add((Tr) element);
			}
		}

		return Collections.unmodifiableList(rows);
	}

	/**
	 *  
	 * @return the THead, TBodies and TFoot elements for the table if they exist or creates them if they do not. 
	 */
	public HeadBodyFoot createOrGetHeadBodyFoot() {
		THead head = this.getHead();
		if (head == null) {
			head = new THead();
			this.addPageElement(head);
		}

		final List<TBody> bodies = this.findMyBodies();
		if (CollectionUtils.isEmpty(bodies)) {
			final TBody body = new TBody();
			this.addPageElement(body);
			bodies.add(body);
		}

		TFoot foot = this.getFoot();
		if (foot == null) {
			foot = new TFoot();
			this.addPageElement(foot);
		}

		return new HeadBodyFoot(head, bodies, foot);
	}

	/**
	 * A DTO that contains the head, foot and one body for the table.
	 * @author J Patrick Davenport
	 *
	 */
	static class HeadBodyFoot {
		private THead		head;
		private TFoot		foot;
		private List<TBody>	bodies;

		public HeadBodyFoot(final THead _head, final List<TBody> _body, final TFoot _foot) {
			this.bodies = _body;
			this.head = _head;
			this.foot = _foot;
		}

		public THead getHead() {
			return this.head;
		}

		public TFoot getFoot() {
			return this.foot;
		}

		public List<TBody> getBodies() {
			return this.bodies;
		}
	}

	/**
	 * Valid values for the rules attribute of the Table.
	 * @author J Patrick Davenport
	 *
	 */
	enum Rules {

		NONE("none"), GROUP("group"), ROWS("rows"), COLS("cols"), ALL("all");

		Rules(final String _value) {
			this.value = _value;
		}

		private String	value;

		@Override
		public String toString() {
			return this.value;
		};

	}

	/**
	 * Valid values for the frame attribute of the table
	 * @author J Patrick Davenport
	 *
	 */
	enum Frame {

		VOID("void"), ABOVE("above"), BELOW("below"), HSIDES("hsides"), LHS("lhs"), RHS("rhs"), VSIDES("vsides"), BOX("box"), BORDER("border");

		Frame(final String _value) {
			this.value = _value;
		}

		private String	value;

		@Override
		public String toString() {
			return this.value;
		};

	}

}
